# -*- encoding: utf-8 -*-

"""
@File:      tc_libmnl_libmnl_func_003.py
@Time:      2024/03/29 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libmnl_libmnl_func_003.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libmnl libmnl-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >libmnl_test3.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libmnl/libmnl.h>
#include <linux/netlink.h>
#include <sys/select.h> // for select()

int main() {
    struct mnl_socket *nl;
    char buf[MNL_SOCKET_BUFFER_SIZE];
    int ret;
    struct timeval tv;
    fd_set readfds;
    int fd;

    nl = mnl_socket_open(NETLINK_GENERIC);
    if (nl == NULL) {
        perror("mnl_socket_open");
        exit(EXIT_FAILURE);
    }

    fd = mnl_socket_get_fd(nl);

    FD_ZERO(&readfds);        // 清空文件描述符集
    FD_SET(fd, &readfds);     // 加入netlink套接字

    // 设置为1秒超时
    tv.tv_sec = 1;
    tv.tv_usec = 0; 

    // 使用select等待套接字上的数据
    ret = select(fd + 1, &readfds, NULL, NULL, &tv);
    if (ret == -1) {
        perror("select");
        exit(EXIT_FAILURE);
    } else if (ret == 0) {
        printf("Timeout reached. No incoming data within 1 second.\\n");
    } else {
        if (FD_ISSET(fd, &readfds)) {
            // 有数据可以读取
            ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
            if (ret == -1) {
                perror("mnl_socket_recvfrom");
                exit(EXIT_FAILURE);
            } else {
                printf("Received message, ret=%d\\n", ret);
                // 这里可以根据需要添加进一步处理接收到的消息的代码
            }
        }
    }

    mnl_socket_close(nl);
    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o libmnl_test3 libmnl_test3.c -lmnl")
        code, libmnl_result = self.cmd("./libmnl_test3")
        self.assertIn("Timeout reached. No incoming data within 1 second", libmnl_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf libmnl_test3.c libmnl_test3")
